import React, {useEffect, useState} from 'react';
import {Button, Image, Input, View} from '@tarojs/components';
import headUrl from '@/app/asserts/head.jpg';

import styles from './index.module.scss';
import {query, submit} from "@/_framework/services/Data";
import {uploadImage} from "@/_framework/services/Upload";
import {infoToast} from "@/_framework/services/Taro";
import Submit from "@/_framework/components/Submit";


const Index: React.FC<any> = ({onSuccess}) => {
    const [head, setHead] = useState<any>('');
    const [nick, setNick] = useState<any>('');
    const [isReady, setIsReady] = useState(false);

    useEffect(() => {
        load();
    }, []);

    const load = async () => {
        const {nickname, avatar} = await query('turing/userInfo/getAuthInfo')
        setNick(nickname || 'momo')
        setHead(avatar || headUrl)
        setIsReady(nickname && avatar)
    };


    const chooseAvatar = async (e) => {
        const {url} = await uploadImage(e.detail.avatarUrl);
        if (url) {
            setHead(url);
            setIsReady(true);
        }

    };

    const inputNickname = async ({value: _nick}) => {
        setNick(_nick);
        setIsReady(_nick.length > 0);
    };

    const updateUser = async () => {
        if (!isReady) {
            infoToast("请录入用户信息")
            return
        }
        const avatar = cleanHead()
        const result = await submit("turing/userInfo/updateAuthInfo", {avatar, nickname: nick})
        if (!result) {
            infoToast("更新用户信息失败，请重试！")
            return
        }
        onSuccess()

    };
    const cleanHead = () => {
        if (head.startsWith('/app')) {
            return ''
        }
        return head

    }

    return (
        <View className={styles.page}>
            <View className={styles.page_head}>
                <Image className={styles.page_head_image} src={head}></Image>
                <Button className={styles.page_head_button} openType='chooseAvatar'
                        onChooseAvatar={chooseAvatar}>
                </Button>
            </View>


            <View className={styles.body_input}>
                <View className={styles.input_label}>昵称</View>
                <Input
                    className={styles.input}
                    type='nickname'
                    placeholder='请输入昵称'
                    value={nick}
                    onInput={(e) => inputNickname({value: e.detail.value})}
                    onConfirm={(e) => inputNickname({value: e.detail.value})}
                />
            </View>

            <Submit isReady={isReady} onSuccess={updateUser}></Submit>


        </View>
    );
};

export default Index;
